var createError = require('http-errors');  //错误处理
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var session = require("express-session");
var RedisStore = require("connect-redis")(session)
var path = require("path")
var fs = require("fs")
var png = require('./routes/png')

// var indexRouter = require('./routes/index');
// var usersRouter = require('./routes/users');
var blog = require("./routes/blog")
var user = require("./routes/user")

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');


const ENV = process.env.NODE_ENV
if (ENV !== 'production') {
  // 开发环境 / 测试环境
  app.use(logger('dev'));
} else {
  // 线上环境
  const logFileName = path.join(__dirname, 'logs', 'access.log')
  const writeStream = fs.createWriteStream(logFileName, {
    flags: 'a'
  })

  logger.token('localDate',function getDate(req) {
    let date = new Date();
    return date.toLocaleString()
   })
  
   logger.token('ip',function getDate(req) {
    let ip = req.headers['x-forwarded-for'] 　||　req.headers['x-real-ip']
      return ip 
    })
  

    logger.format('combined', '[:ip]  - :remote-user [:localDate] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"');

  app.use(logger('combined', { stream: writeStream }));


}
app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  //Access-Control-Allow-Headers ,可根据浏览器的F12查看,把对应的粘贴在这里就行
  res.header('Access-Control-Allow-Methods', '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
  next();
});


app.use(express.json({limit: '50mb'}));  //处理post请求传入数据   req.body获取数据
app.use(express.urlencoded({ extended: false }));     //获取post请求的的 表单数据  req.body获取数据
app.use(cookieParser());   //可以通过req.cookie 获取cookie
app.use(express.static(path.join(__dirname, 'public')));

/* app.use('/', indexRouter); 
app.use('/users', usersRouter); */

const RedisClient = require('./db/redis')


RedisClient.get('time', (err, num) => {
  
  // 如果不存在，则进行赋值
  if (err || num === null) 
  {
    RedisClient.set('time', Date.now() + "");
    return;
  }
  return;

})


const sessionStore = new RedisStore({
  client:RedisClient
})

app.use(session({
         secret:"WJLOT_123123#",
         cookie:{
           path:"/",
           httpOnly:true,
          maxAge:24*60*60*1000
         },
         store:sessionStore
}))

app.use("/api/blog",blog)
app.use("/api/user",user)


app.use("/png",png);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'dev' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
